var express= require("express");
var router=express.Router();
var md5=require('md5');
var mysql=require('mysql');
var dbConfig=require('../db/dbconfig');
var userSQL=require('../db/usr'); 
var pool=mysql.createPool(dbConfig.mysql);
var cheerio=require('./cheerio');

var responseJSON=function(res,ret){
    if(typeof ret === 'undefined') { 
        res.json({code:'-200',msg: '操作失败'}); 
    } else { 
        res.json(ret); 
    }
}

router.get('/addUsr',function(req,res,next){
    pool.getConnection(function(err,connection){
        var param=req.query || req.params;
        connection.query(userSQL.insert,[param.name,md5(param.password)],function(err,result){
            if(result){
                result={
                    code:200,
                    msg:'增加成功'
                }
            }
            responseJSON(res,result);
            connection.release();
        })
    })
})

router.get('/query',function(req,res,next){
    pool.getConnection(function(err,connection){
        connection.query(userSQL.queryAll,function(err,result){
            if(result){
                result={
                    code:200,
                    msg:'查询成功',
                    data:result
                }
            }
            responseJSON(res,result);
            connection.release();
        })
    })
})

router.post('/update',function(req,res,next){
    pool.getConnection(function(err,connection){
        console.log(req.body)
        var param=req.body || req.params;
        connection.query(userSQL.update,[md5(param.password),param.name],function(err,result){
            if(result){
                result={
                    code:200,
                    msg:'修改成功'
                }
            }
            responseJSON(res,result);
            connection.release();
        })
    })
})

router.get('/delete',function(req,res,next){
    pool.getConnection(function(err,connection){
        var param=req.query || req.params;
        connection.query(userSQL.delete,[param.name],function(err,result){
            if(result){
                result={
                    code:200,
                    msg:'删除成功'
                }
            }
            responseJSON(res,result);
            connection.release();
        })
    })
})

router.get('/cheerio',function(req,res,next){
   cheerio(req,res,next)
})


module.exports=router;